package com.example.springframeworklearning.controller;

import com.example.springframeworklearning.domain.Order;
import com.example.springframeworklearning.validator.OrderConstraintValidator;
import com.example.springframeworklearning.validator.annotation.ValidateOrder;
import org.springframework.validation.annotation.Validated;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

/**
 * @author luo
 * @since 2022/9/21 15:31
 */
@RestController
@RequestMapping("/validate")
public class ValidatorController {


    /**
     * 在这里把 validator 绑定到 DataBinder 上可以实现
     * 如果controller 方法参数中有 @Validated 注解，则 当数据绑定完成之后调用 validator
     *
     * @param binder
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.addValidators(new OrderConstraintValidator(null));
    }


    @PostMapping("/createOrder")
    public String createOrder(@RequestBody /*@ValidateOrder*/ @Validated Order order) {

        return "已保存：" + order;
    }


}
